import React, { useState, useEffect } from 'react';
import './index.less';
import { handleDebounce } from '../../utils';

interface Props {
  children?: any;
  time?: number; // 防抖时间
  className?: string; // 外置样式
  disabled?: boolean; // 置灰
  bgColor?: string;
  isShow?: boolean;
  style?: Object;
  onClick?: Function;
}
let timers: any = null;
const IrrButton = (props: Props) => {
  const {
    children,
    time = 500,
    className = '',
    disabled = false,
    bgColor = '#4c85c7',
    isShow = true,
    onClick = () => {},
  } = props;
  const [isOk, setIsOk] = useState<boolean>(true);
  const onBtnClick = () => {
    timers && clearTimeout(timers);
    if (disabled) return;
    if (isOk) {
      setIsOk(false);
      setTimeout(() => {
        setIsOk(true);
      }, 460);
    }
  };

  useEffect(() => {
    if (!isOk) {
      onClick();
    }
    return () => {
      timers && clearTimeout(timers);
      timers = null;
    };
    // eslint-disable-next-line
  }, [isOk]);
  const getClassName = (): string => {
    return `irr_single_btn ${className} ${
      disabled ? 'irr_single_btn--disabled' : ''
    }`;
  };
  const getStyle = () => {
    const { style = {} } = props;
    return {
      backgroundColor: bgColor,
      display: isShow ? 'block' : 'none',
      ...style,
    };
  };
  return (
    <div
      className={getClassName()}
      style={getStyle()}
      onClick={handleDebounce(onBtnClick, time, true)}
    >
      {children}
    </div>
  );
};

export default IrrButton;
